#include "connectionstore.h"
#include "connection.h"
#include "../accountstore.h"
#include "../chatwidgetstore.h"

namespace Kajim
{
namespace XMPP
{

ConnectionStore::ConnectionStore(QObject *parent)
    : QObject(parent)
{
}

ConnectionStore * ConnectionStore::instance()
{
    if (ConnectionStore::inst == 0) {
        ConnectionStore::inst = new ConnectionStore();
    }

    return ConnectionStore::inst;
}

Connection * ConnectionStore::accountConnection(int h)
{
    ::Kajim::AccountStore * accountStore = Kajim::AccountStore::instance();

    ::Kajim::Account * account = accountStore->account(h);
    if (account == 0) {
        // account with given name doesn't exist, so delete corresponding
        // connection if it's in the pool
        if (connections.contains(h)) {
            Connection * conn = connections[h];
            connections.remove(h);
            delete conn;
        }
        return 0;
    }

    if (!connections.contains(h)) {
        // create new connection
        Connection * conn = new Connection(h);
        // connect signal
        ::Kajim::ChatWidgetStore * chatStore = ::Kajim::ChatWidgetStore::instance();
        connect(conn, SIGNAL(messageReceived(int, const QString &, const QString &, const QString &)),
                chatStore, SLOT(incomingMessage(int, const QString &, const QString &, const QString &)));
        connections[h] = conn;
    }

    return connections[h];
}

ConnectionStore * ConnectionStore::inst = 0;

}
}

